# _*_ encoding: utf-8 _*_
# __author__ = 'lx'
import datetime
import os

# os.environ["IMAGEMAGICK_BINARY"] = "D:\\software\\ImageMagick-7.1.0-Q16-HDRI\\magick.exe"

from moviepy.editor import *
from constant import VIDEO_RESULTS, FONT_PATH

simsun = os.path.join(FONT_PATH, 'simsun.ttc').replace("\\", "/")
print(simsun)

def template_on_video(text_list,video_path,img_path,bgm_path,img_pos=0.25,volumex=0.01,text_font=simsun,text_color='black',text_font_size=40):
    """
    测试生成视频：
    注意
    字体的路径只能使用linux的“/”, 否则加载不了
    """
    b = 0.75
    # 加载视频，同时设置视频的位置（25%，0%）的坐标处
    video_clip = VideoFileClip(video_path).set_position((1-b,0),relative=True)
    W, H = video_clip.size
    # 视频变为0.75倍
    video_clip = video_clip.resize(b)
    # 加载图片
    img_clip = ImageClip(img_path)
    # 计算出合适的尺寸
    img_resize = (1-b)*W/(3*img_clip.size[0])
    # 设置图片的持续时间、位置、尺寸
    img_clip = img_clip.set_duration(video_clip.end).set_position(((1-b)*W/3, img_pos * H)).resize(img_resize)

    text_clips = []
    # 自动切分
    for i in text_list:
        # 设置字幕，字体大小、颜色、字体文件
        text_clips.append(
        TextClip(i, fontsize=text_font_size, color=text_color, font=text_font,method='caption',size=(0.95*W,None)).set_duration(video_clip.end / len(text_list))
        )
    text_clips = concatenate_videoclips(text_clips).set_position((0.05*W,(b+0.05)*H))
    # 设置音频
    audio = AudioFileClip(bgm_path).subclip(0, video_clip.end)
    final_clip = CompositeVideoClip([video_clip, img_clip, text_clips], size=(W, H),
                                    bg_color=[255, 255, 255]).set_audio(audio).volumex(volumex)
    filename = datetime.datetime.now().strftime('%Y%m%d%H%M')
    path = os.path.join(VIDEO_RESULTS, f"V{filename}.mp4")
    final_clip.write_videofile(path, fps=24, codec='libx264')       # bitrate='300k'
    return 'media/results/video'+'/V' + filename + '.mp4'


if __name__ == '__main__':
    text_list = ['健身房锻炼(⊙o⊙)','怎么这么棒(๑•̀ㅂ•́)و✧','肌肉好强']
    template_on_video(text_list,"../media/material/video/test1.mp4","../static/material/img/youtube_logo.png","../media/material/music/mzt.mp3")